/*
 * @Author: szx
 * @Date: 2022-07-01 15:43:09
 * @LastEditTime: 2022-07-05 17:11:59
 * @Description: 主要的界面，包括header、input和list三个界面
 * @FilePath: \link_jump\src\pages\Home.tsx
 */
import React, { useState, useEffect } from 'react';
import { StyleSheet, View } from 'react-native';

import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import { Task, TasksList } from '../components/TasksList';
import { TodoInput } from '../components/TodoInput';
import storage from '../utils/storage';
import Clipboard from '@react-native-clipboard/clipboard';
import Toast from 'react-native-toast-message';
// storage.remove({ key: 'task' });
export function Home() {
  const [tasks, setTasks] = useState<Task[]>([]);

  useEffect(() => {
    storage
      .load({
        key: 'task'
      })
      .then((task) => {
        console.log('读取', task);
        if (task) {
          setTasks(task);
        }
      })
      .catch((err) => {
        console.warn(err.message);
        switch (err.name) {
          case 'NotFoundError':
            console.warn('没找到数据');
            break;
          case 'ExpiredError':
            Toast.show({
              type: 'error',
              text1: '读取错误！',
              position: 'bottom',
              visibilityTime: 2000,
              bottomOffset: 70
            });
            console.log('读取错误');
            break;
        }
      });
  }, []);

  function handleAddTask(newTaskName: string, newTaskLink: string) {
    const newTask = {
      id: new Date().getTime().toString(),
      name: newTaskName,
      link: newTaskLink,
      checked: false
    };
    // console.log('newTask', newTask);
    const newTasks = [...tasks, newTask];
    storage.save({
      key: 'task', // 注意:请不要在key中使用_下划线符号!
      data: newTasks,
      expires: null
    });
    setTasks(newTasks);
    Toast.show({
      type: 'info',
      text1: '添加成功',
      text2: `name:${newTask.name} ,link:${newTask.link}`,
      position: 'bottom',
      visibilityTime: 2000,
      bottomOffset: 70
    }); // console.log('save tasks', newTasks);
  }

  function handleCheckTask(index: number) {
    const newTasks = tasks.map((task, i) => {
      if (i === index) return { ...task, checked: !task.checked };
      else return task;
    });
    setTasks(newTasks);
    // console.log('Home handleCheckTask', tasks);
  }
  function handleAllCheckBox(state: boolean) {
    const newTasks = tasks.map((task) => ({ ...task, checked: state }));
    setTasks(newTasks);
    // console.log(newTasks);
  }
  function handleRemoveTask() {
    const newTasks = tasks.filter((task) => !task.checked);
    setTasks(newTasks);
    storage.save({
      key: 'task', // 注意:请不要在key中使用_下划线符号!
      data: newTasks,
      expires: null
    });
    Toast.show({
      type: 'success',
      text1: '删除成功',
      text2: `总共删除${tasks.length - newTasks.length}条`,
      position: 'bottom',
      visibilityTime: 2000,
      bottomOffset: 70
    });
  }

  function updateTaskLink(id: string, newLink: string) {
    const newTasks = tasks.map((task) => {
      if (task.id === id) return { ...task, link: newLink };
      else return task;
    });
    storage.save({
      key: 'task', // 注意:请不要在key中使用_下划线符号!
      data: newTasks,
      expires: null
    });
    // console.log(newTasks);
    setTasks(newTasks);
    Toast.show({
      type: 'success',
      text1: '修改成功',
      position: 'bottom',
      visibilityTime: 2000,
      bottomOffset: 70
    });
  }

  function exportLink() {
    const exports = tasks.filter((task) => task.checked).map((task) => ({ name: task.name, link: task.link }));
    const res = JSON.stringify(exports);
    Clipboard.setString(res);
    Toast.show({
      type: 'success',
      text1: '导出到剪切板成功',
      text2: res,
      position: 'bottom',
      visibilityTime: 2000,
      bottomOffset: 70
    });
  }

  async function importLink() {
    try {
      const text = await Clipboard.getString();
      const arr = JSON.parse(text);
      if (arr instanceof Array) {
        if (arr.length === 0) {
          Toast.show({
            type: 'info',
            text1: '没有数据',
            position: 'bottom',
            visibilityTime: 2000,
            bottomOffset: 70
          });
          return;
        }
        const newAddTasks = arr.map((task, index) => {
          return {
            id: new Date().getTime().toString() + index,
            name: task?.name,
            link: task?.link,
            checked: false
          };
        });
        const newTasks = [...tasks, ...newAddTasks];
        storage.save({
          key: 'task', // 注意:请不要在key中使用_下划线符号!
          data: newTasks,
          expires: null
        });
        setTasks(newTasks);
        Toast.show({
          type: 'success',
          text1: '导入剪切板成功',
          position: 'bottom',
          visibilityTime: 2000,
          bottomOffset: 70
        });
      } else {
        throw '不是数组类型，报错';
      }
    } catch (err) {
      Toast.show({
        type: 'error',
        text1: '导入剪切板错误',
        text2: String(err),
        position: 'bottom',
        visibilityTime: 2000,
        bottomOffset: 70
      });
    }
  }
  return (
    <View style={styles.container}>
      <Header tasksCounter={tasks.length} importLink={importLink} />

      <TodoInput addTask={handleAddTask} />

      <TasksList tasks={tasks} checkTask={handleCheckTask} updateTaskLink={updateTaskLink} />

      <Footer tasks={tasks} handleAllCheckBox={handleAllCheckBox} removeTask={handleRemoveTask} exportLink={exportLink} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#EBEBEB'
  }
});
